package com.ermax.aircond.report.web.bean;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ermax.aircond.common.domain.ReadMachineData;
import com.ermax.aircond.common.service.ReadMachineDataService;
import com.ermax.aircond.maintain.domain.Machine;
import com.ermax.aircond.maintain.service.MaintainService;
import com.ermax.aircond.manage.domain.RealTimeControl;
import com.ermax.aircond.report.domain.ErrorDetail;
import com.ermax.aircond.report.service.AuditLogService;
import com.ermax.aircond.resource.MessageBundle;
import com.ermax.aircond.util.service.MachineCommandService;
import com.ermax.aircond.util.web.bean.DataTableBean;

@Scope("view")
@Component
public class ErrorMachineBean extends DataTableBean implements java.io.Serializable {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(ErrorMachineBean.class);
	private static final DateFormat DATA_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");

	@Resource(name = "readMachineDataService")
	private ReadMachineDataService readMachineDataService;

	@Resource(name = "maintainService")
	private MaintainService maintainService;

	@Resource(name = "machineCommandService")
	private MachineCommandService machineCommandService;
	
	@Resource(name = "auditLogService")
	private AuditLogService auditLogService;

	private List<ErrorDetail> errorDetails;

	@PostConstruct
	public void init() {
		try {
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}

	private void reset() throws Exception {
		errorDetails = new ArrayList<ErrorDetail>();
		
		List<ReadMachineData> readMachineDatas = readMachineDataService.getErrorNidData("E3");
		
		for (int i = 0; i < readMachineDatas.size(); i++) {			
			ReadMachineData readMachineData = readMachineDatas.get(i);
			
											
			if(readMachineData != null){
				ErrorDetail errorDetail = new ErrorDetail();
				errorDetail.setReadMachineData(readMachineData);
				
				RealTimeControl realTimeControl = new RealTimeControl();				
				List<String> values = machineCommandService.extractMachineData(readMachineData.getData());
				for(int j=0; j<values.size(); j++){
					realTimeControl = machineCommandService.translateCommand(realTimeControl, values.get(j));
				}														
				errorDetail.setRealTimeControl(realTimeControl);
								
				int nid = readMachineData.getNid();				
				Machine machine = maintainService.getMachineByNid(nid);				
				if(machine != null){
					realTimeControl.setMachine(machine);
				}
				
				errorDetails.add(errorDetail);
				
			}							
			
		}

	}
	
	public void genExcel(ActionEvent event) throws Exception {
		Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
		HSSFWorkbook workbook = auditLogService.convertErrorDetailstoExcel(getErrorDetails(), locale);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
		response.reset();

		StringBuilder sbHeader = new StringBuilder();
		sbHeader.append("attachment; filename=\"");
		sbHeader.append("ERROR_REPORT_");
		sbHeader.append(DATA_FORMAT.format(new Date()));
		sbHeader.append("_");
		sbHeader.append(".xls\"");

		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", sbHeader.toString());

		ServletOutputStream out = response.getOutputStream();
		workbook.write(out);
		FacesContext.getCurrentInstance().responseComplete();
	}

	public List<ErrorDetail> getErrorDetails() {
		return errorDetails;
	}

	public void setErrorDetails(List<ErrorDetail> errorDetails) {
		this.errorDetails = errorDetails;
	}
}
